package org.seed.rpc.clientstub;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.seed.rpc.common.util.IconSpecialUtil;
import org.seed.rpc.core.Constants;
import org.seed.rpc.core.RegistryClient;
import org.seed.rpc.core.RegistryOperator;
import org.seed.rpc.core.RuntimeLocal;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;


@Slf4j
@Configuration
@AutoConfigureAfter(RpcClientAutoConfigure.class)
@ConditionalOnProperty("rpc.local.registry")
public class RegistryConfigChangeListener implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        RegistryClient registryClient = RuntimeLocal.getRegistryClient();
        reloadRegistryData(registryClient);
        registryClient.prefixOnChange(Constants.SERVICE_REGISTRY_KEY_PREFIX, new Consumer() {
            @Override
            public void accept(Object o) {
                reloadRegistryData(registryClient);
            }
        });
        log.info("\uD83D\uDC42 \uD83D\uDC42 rpc-client open on listening registry config change");
    }

    private void reloadRegistryData(RegistryClient registryClient) {
        Map<String, List<String>> map = RegistryOperator.getServiceEndpointMap(registryClient);
        RuntimeLocal.cacheLocalServiceNameEndpointMap(map);
        log.info(IconSpecialUtil.randomIcon() + ": " + new Gson().toJson(map));
    }

}
